package com.itheima.controller;

import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * CachePut-将返回值放入Redis
     */
    @PostMapping
    @CachePut(cacheNames = "userCache",key = "#user.id")//1. (推荐使用)-如果使用Spring Cache缓存数据，生成的KEY的格式为：cacheNames::key
    //@CachePut(cacheNames = "userCache",key = "#result.id")//2. result表示该方法的返回结果 .表示对象导航
    //@CachePut(cacheNames = "userCache",key = "#p0.id")//3. p0表示第一个参数
    //@CachePut(cacheNames = "userCache",key = "#a0.id")//4. a0表示第一个参数
    //@CachePut(cacheNames = "userCache",key = "#root.args[0].id")//5. root.args[0]表示第一个参数
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }

    /**
     * CacheEvict-将一条数据从缓存中删除
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "userCache",key = "#id")//KEY的生成：cacheNames::key
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

    /**
     * CacheEvict-将多条数据从缓存中删除
     */
	@DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true)//allEntries-所有的键值对
    public void deleteAll(){
        userMapper.deleteAll();
    }


    /**
     * Cacheable-在方法执行前先查询缓存中是否有数据，如果有数据，则直接返回缓存数据；如果没有缓存数据，调用方法并将方法返回值放到缓存中
     * 若缓存中查到数据则将数据通过反射设置给该方法的返回值
     * 若缓存中未查到数据则将执行查询数据库逻辑
     */
    @GetMapping
    @Cacheable(cacheNames = "userCache",key = "#id")//KEY的生成：cacheNames::key
    public User getById(Long id){
        User user = userMapper.getById(id);
        return user;
    }

}
